import React, { Component } from "react";
import { DatePicker, Table, Input, Badge, Radio } from "antd";
import { connect } from "dva";
import moment from "moment";
import { Link } from "dva/router";
import { getHashUrlParams, setUrlParams } from 'src/utils/utils';
import TemplateApprove from './components/TemplateApprove';
import styles from "./BackLog.less";
import { getChannelText } from "../../../channelType";

const { Search } = Input;
const { RangePicker } = DatePicker;

@connect(stores => ({
  messageData: stores.systemManager,
  channelDictionaryModel: stores.channelDictionaryModel,
}))
class BackLog extends Component {

  constructor(props) {
    super(props);
    const { type } = getHashUrlParams();
    this.state = {
      pushChannelType: [""],
      ownerDept: [""],
      auditStatus: [""],
      sourceName: "",
      timeCreateOrder: "desc",
      timeUpdateOrder: "",
      timeCreateTo: "",
      timeCreateEnd: "",
      pageNum: 1,
      pageSize: 10,
      radioValue: type && Number(type) === 1 ? 1 : 0, // 0-消息源审批，1-模板审批
    };
  }

  componentDidMount() {
    const { dispatch, history } = this.props;
    dispatch({
      type: "systemManager/fetchMessageBackLog",
      payload: {
        pageNum: 1,
        pageSize: 10,
        timeCreateOrder: "desc",
        timeUpdateOrder: ""
      }
    });
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {}
    });
    const {
      ownerDept,
      auditStatus,
      timeUpdateOrder,
      timeCreateOrder,
      timeCreateTo,
      timeCreateEnd,
      sourceName,
      pushChannelType
    } = this.state;
    const temp = {
      timeUpdateOrder,
      timeCreateOrder,
      ownerDept: ownerDept[0],
      auditStatus: auditStatus[0],
      timeCreateTo,
      pushChannelType: pushChannelType[0],
      timeCreateEnd,
      sourceNameOrOwnerName: sourceName
    };
    dispatch({
      type: "systemManager/fetchMessBackDept",
      payload: { ...temp }
    });
    setUrlParams({}, history);
  }

  renderState = text => {
    if (text === 1) {
      return <Badge status="success" text="审批通过" />;
    }
    if (text === -1) {
      return <Badge status="default" text="未通过" />;
    }
    return <Badge status="warning" text="待审批" />;
  };

  renderType = text => {
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    return <span>{getChannelText(channelsTypesData, text)}</span>;
  }

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          timeCreateTo: e[0].format("YYYY-MM-DD 00:00:00"),
          timeCreateEnd: new Date(e[1].format("YYYY-MM-DD 23:59:59")),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          timeCreateTo: "",
          timeCreateEnd: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleSearch = e => {
    this.setState(
      {
        sourceName: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  returnSort = (sorter, type) => {
    if (
      sorter.order &&
      sorter.columnKey === type &&
      sorter.order === "ascend"
    ) {
      return "asc";
    }
    if (
      sorter.order &&
      sorter.columnKey === type &&
      sorter.order === "descend"
    ) {
      return "desc";
    }
    return "";
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { ownerDept, auditStatus, pushChannelType } = this.state;
    this.setState(
      {
        pageNum:
          (filters.ownerDeptName && filters.ownerDeptName !== ownerDept) ||
            (filters.auditStatus && filters.auditStatus !== auditStatus) ||
            (filters.pushChannelType &&
              filters.pushChannelType !== pushChannelType)
            ? 1
            : current,
        pageSize,
        timeUpdateOrder: this.returnSort(sorter, "timeUpdate"),
        timeCreateOrder: this.returnSort(sorter, "timeCreate"),
        ownerDept: filters.ownerDeptName ? filters.ownerDeptName : [""],
        auditStatus: filters.auditStatus ? filters.auditStatus : [""],
        pushChannelType: filters.pushChannelType
          ? filters.pushChannelType
          : [""]
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const {
      ownerDept,
      auditStatus,
      pageSize,
      timeUpdateOrder,
      timeCreateOrder,
      pageNum,
      timeCreateTo,
      timeCreateEnd,
      sourceName,
      pushChannelType
    } = this.state;
    const { dispatch } = this.props;
    const temp = {
      timeUpdateOrder,
      timeCreateOrder,
      ownerDept: ownerDept[0],
      auditStatus: auditStatus[0],
      timeCreateTo,
      pushChannelType: pushChannelType[0],
      timeCreateEnd,
      sourceNameOrOwnerName: sourceName === "" ? undefined : sourceName
    };
    dispatch({
      type: "systemManager/fetchMessageBackLog",
      payload: {
        pageNum: String(pageNum),
        pageSize: String(pageSize),
        ...temp
      }
    });
    dispatch({
      type: "systemManager/fetchMessBackDept",
      payload: { ...temp, ownerDept: "" }
    });
    // dispatch({ type: "addPlan/getPushChannel", payload: { ...temp } });
  };

  render() {
    const { messageData, history } = this.props;
    const { channelDictionaryModel } = this.props;
    const { CHANNEL_VALUE = [] } = channelDictionaryModel;
    const {
      messDeptList = [],
      messageBacklogLoading,
      messageBackLogList = [],
      messageTotalCount = 0
    } = messageData;
    const { pageNum, radioValue, timeCreateTo, timeCreateEnd, sourceName } = this.state;
    const deptList = messDeptList.map(item => {
      const temp = { text: item.ownerDeptName, value: item.ownerDept };
      return temp;
    });
    const columns = [
      {
        title: "消息源名称",
        dataIndex: "sourceName",
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "渠道类型",
        dataIndex: "pushChannelType",
        render: text => (text ? this.renderType(text) : "--"),
        filterMultiple: false,
        filters: CHANNEL_VALUE
      },
      {
        title: "渠道名称",
        dataIndex: "pushChannelName"
        // filters: [],
        // filterMultiple: false
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName",
        filters: deptList,
        filterMultiple: false,
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "管理者",
        dataIndex: "owner",
        render: text => (
          <span>
            {text && JSON.parse(text) && JSON.parse(text).length > 0
              ? JSON.parse(text)[0].name
              : "---"}
          </span>
        )
      },
      {
        title: "状态",
        dataIndex: "auditStatus",
        filters: [
          { text: "通过", value: 1 },
          { text: "未通过", value: -1 },
          { text: "待审核", value: 0 }
        ],
        filterMultiple: false,
        render: text => <div>{this.renderState(text)}</div>
      },
      {
        title: "提交时间",
        dataIndex: "timeCreate",
        sorter: true,
        ellipsis: true,
        defaultSortOrder: "descend",
        render: (text, { timeCreate }) =>
          timeCreate ? moment(timeCreate).format("YYYY-MM-DD HH:mm:ss") : "---"
      },
      {
        title: "审批时间",
        dataIndex: "timeUpdate",
        sorter: true,
        ellipsis: true,
        // defaultSortOrder: "descend",
        render: (text, { timeHandle }) =>
          timeHandle ? moment(timeHandle).format("YYYY-MM-DD HH:mm:ss") : "---"
      },
      {
        title: "操作",
        dataIndex: "operate",
        fixed: "right",
        width: 100,
        render: (text, record) => {
          const states = {
            operate: "audit",
            pendingEventId: record.pendingEventId,
            specificEventId: record.specificEventId
          };
          const detail = {
            operate: "detail",
            pendingEventId: record.pendingEventId,
            specificEventId: record.specificEventId
          };
          return (
            <span>
              {record.auditStatus === 0 ? (
                <Link
                  to={`/systemManager/systemMessage/messageBacklog/messageDetail?key=${JSON.stringify(
                    states
                  )}`}
                >
                  审批
                </Link>
              ) : (
                  <Link
                    to={`/systemManager/systemMessage/messageBacklog/messageDetail?key=${JSON.stringify(
                      detail
                    )}`}
                  >
                    查看详情
                  </Link>
                )}
            </span>
          );
        }
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>待办事项</div>
        <div style={{ padding: '24px' }}>
          <div className={styles.topSearch}>
            <Radio.Group value={radioValue} onChange={e => this.setState({ radioValue: e.target.value })}>
              <Radio.Button value={0}>消息源审批</Radio.Button>
              <Radio.Button value={1}>模板审批</Radio.Button>
            </Radio.Group>
            <div>
              提交时间：
            <RangePicker
                style={{ width: 224, marginRight: 21 }}
                onChange={this.dateChange}
                disabledDate={this.handleDisabledDate}
              />
              <Search
                placeholder={radioValue === 0 ? "管理员姓名、消息源名称" : "模板名称"}
                // onSearch={value => console.log(value)}
                style={{ width: 272 }}
                onSearch={this.handleSearch}
              />
            </div>
          </div>
          {
            radioValue === 0 ?
              <Table
                style={{ background: '#fff' }}
                rowKey={record => record.timeCreate}
                columns={columns}
                scroll={messageBackLogList.length === 0 ? { x: false } : { x: 1200 }}
                dataSource={messageBackLogList}
                locale={{ emptyText: "暂无数据！" }}
                size="middle"
                onChange={(e, filters, sorter) =>
                  this.handleTableChange(e, filters, sorter)
                }
                loading={messageBacklogLoading}
                pagination={{
                  defaultPageSize: 10,
                  showQuickJumper: true,
                  showSizeChanger: true,
                  current: pageNum,
                  total: messageTotalCount,
                  showTotal: total => `共有 ${total} 条`
                }}
              /> :
              <TemplateApprove
                timeCreateTo={timeCreateTo}
                timeCreateEnd={timeCreateEnd}
                sourceName={sourceName}
                history={history}
                beforeNavigate={() => setUrlParams({ type: this.state.radioValue}, this.props.history)}
              />
          }
        </div>
      </div>
    );
  }
}

export default BackLog;
